package com.bwie.controller;

import java.io.File;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bwie.entity.Article;
import com.bwie.entity.QueryVo;
import com.bwie.service.ArticleService;
import com.github.pagehelper.PageInfo;
import com.sun.source.tree.NewArrayTree;

@Controller
public class ArticleController {

	@Autowired
	private ArticleService articleService;
	
	@RequestMapping("/list")
	public String list(@RequestParam(defaultValue="1")Integer pageNum,QueryVo qv,Model model){
		PageInfo<Article> pg = articleService.list(pageNum, qv);
		model.addAttribute("pg", pg);
		model.addAttribute("qv", qv);
		return "list";
	}
	
	@RequestMapping("/toAdd")
	public String toAdd(Model model){
		model.addAttribute("a",new Article());
		return "add";
	}
	@ResponseBody
	@RequestMapping("/upload")
	public String upload(MultipartFile file){
		try {
			if(file!=null&&file.getSize()>0){
				String path="H:/img";
				String fileName=UUID.randomUUID().toString()+file.getOriginalFilename();
				File file2 = new File(path, fileName);
				file.transferTo(file2);
				return "/img/"+fileName;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return null;
	}
	
	@RequestMapping("/add")
	public String add(@ModelAttribute("a")Article a){
		articleService.add(a);
		return "redirect:list";
	}
	
	
}
